package com.foreveross.taskservice.core.domain.task.assign.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.dayatang.utils.DateUtils;
import org.springframework.stereotype.Component;

import com.foreveross.taskservice.core.domain.task.TaskQueueRecordEntity;
import com.foreveross.taskservice.core.domain.task.TaskTemplateAssignDayEntity;
import com.foreveross.taskservice.core.domain.task.TaskTemplateEntity;
import com.foreveross.taskservice.core.domain.task.assign.AssignBuildQueue;
import com.foreveross.taskservice.infra.util.DateUtil;
@Component("weekAssignBuildQueue")
public class WeekBuildQueueBean implements AssignBuildQueue {

	@Override
	public List<TaskQueueRecordEntity> build(TaskTemplateAssignDayEntity ta) {
		List<TaskQueueRecordEntity> list = new ArrayList<TaskQueueRecordEntity>();
		//星期，如果已超过当天的星期值时，则使用下周的星期几
		//这里的周日，值为1
		if(ta.getAssignFlightDay()>0 && ta.getAssignFlightDay()<=7) {
			int week = DateUtils.getDayOfWeek(new Date()); //当天是周几
			int setweek = ta.getAssignFlightDay(); //配置是周几
			Date date = DateUtil.addDay(new Date(), setweek-week);
			TaskTemplateEntity template = ta.getTemplate();
			if(ta.getFutureCycle() > 0){
				//未来第几周，从周一至周日，周日也要算在里面,所有如果当前配置是周日时，要多加一个周期
				int setCycle = setweek == Calendar.SUNDAY ? ta.getFutureCycle()+1 : ta.getFutureCycle();
				for(int cycle = 0; cycle < setCycle; cycle++){
					if(!date.before(DateUtil.getEarlyMorning())){//必须超过今天
						list.add(new TaskQueueRecordEntity(
							template.getFromCity(), template.getFromCityName(), template.getToCity(), template.getToCityName(),
							DateUtil.formatDay(date, "yyyy-MM-dd"), 
							DateUtil.getDateAfter(date, ta.getAssignRoundDay()),
							template.getIsInternational()==null?0:template.getIsInternational().intValue(), template.getIsReturn()==null?0:template.getIsReturn(), 
											template.getGrabChannelId(), template.getGrabChannel(), template.getAreaCode(), template.getAreaName(), template.getAttachHbaseKey(), template.getPriority()));
					}
					date = DateUtil.addDay(date, 7);
				}
			}else{
				list.add(new TaskQueueRecordEntity(
						template.getFromCity(), template.getFromCityName(), template.getToCity(), template.getToCityName(),
						DateUtil.formatDay(date, "yyyy-MM-dd"), 
						DateUtil.getDateAfter(date, ta.getAssignRoundDay()),
						template.getIsInternational()==null?0:template.getIsInternational().intValue(), template.getIsReturn()==null?0:template.getIsReturn(), 
										template.getGrabChannelId(), template.getGrabChannel(), template.getAreaCode(), template.getAreaName(), template.getAttachHbaseKey(), template.getPriority()));
			}
		}
		return list;
	}

}
